import util from './util'
import config from './config'

const showModal = (title, content) => {
  if (mpvuePlatform === 'my') {
    mpvue.showModal({
      title,
      content,
      showCancel: false
    })
  } else {
    mpvue.showModal({
      title,
      content,
      showCancel: false
    })
  }
}

const showToast = (title, duration = 2500, icon = 'none') => {
  if (mpvuePlatform === 'my') {
    mpvue.showToast({
      title: title,
      icon: icon,
      duration: duration
    })
  } else {
    mpvue.showToast({
      title: title,
      icon: icon,
      duration: duration
    })
  }
}

const showLoading = (text) => {
  if (mpvuePlatform === 'my') {
    mpvue.showLoading({
      title: text
    })
  } else {
    mpvue.showLoading({
      title: text
    })
  }
}

const appRequest = (url, data, isObj = true, method = 'post') => {
  if (!isObj) {
    url = url + '?' + util.urlEncode(data)
  }
  const header = {
    Authorization: config.Authorization,
    'X-Requested-With': 'XMLHttpRequest'
  }
  return new Promise((resolve, reject) => {
    wx.request({
      data,
      method,
      header,
      url: config.Domain + url,
      success: function (res) {
        if (res.data.success) {
          var result = res.data.result
          resolve(result)
        } else {
          var errorMsg = ''
          if (res.data.error.message) {
            errorMsg = res.data.error.message
          }
          if (res.data.error.validationErrors) {
            res.data.error.validationErrors.forEach(item => {
              errorMsg += item.message + ','
            })
            errorMsg = errorMsg.substring(0, errorMsg.length - 1)
          }
          showToast('提示信息 : ' + errorMsg)
          reject(res.data)
        }
      }
    })
  })
}

const appApi = {
  showModal,
  showToast,
  showLoading,
  appRequest
}
export default appApi
